package com.mhr.ai.cr.settings

import com.intellij.openapi.components.*
import com.intellij.openapi.project.Project
import com.intellij.util.xmlb.XmlSerializerUtil
import com.mhr.ai.cr.provider.AIProviderFactory
import com.mhr.ai.cr.provider.AIProviderConfig

/**
 * AI 设置状态管理
 * 持久化存储 AI 相关配置到项目级别
 * 支持多提供商分组配置
 */
@State(
    name = "AICodeReviewSettings",
    storages = [Storage("ai-code-review-settings.xml")]
)
@Service(Service.Level.PROJECT)
class AISettingsState : PersistentStateComponent<AISettingsState> {

    // 当前选择的提供商
    var currentProvider: String = AIProviderFactory.ProviderType.DEEPSEEK.name

    // 阿里云通义千问配置
    var dashScopeApiKey: String = ""
    var dashScopeModel: String = "qwen-plus"
    var dashScopeBaseUrl: String = ""

    // DeepSeek配置
    var deepSeekApiKey: String = ""
    var deepSeekModel: String = "deepseek-chat"
    var deepSeekBaseUrl: String = ""

    // 通用参数
    var temperature: Float = 0.7f
    var maxTokens: Int = 2000
    var timeout: Int = 30

    // 功能开关
    var enabled: Boolean = true
    var autoReview: Boolean = false

    // 审核配置
    var reviewLanguage: String = "zh" // zh, en
    var reviewLevel: String = "standard" // basic, standard, strict

    override fun getState(): AISettingsState = this

    override fun loadState(state: AISettingsState) {
        XmlSerializerUtil.copyBean(state, this)
    }

    /**
     * 获取当前提供商类型
     */
    fun getCurrentProviderType(): AIProviderFactory.ProviderType? {
        return AIProviderFactory.getProviderTypeByName(currentProvider)
    }

    /**
     * 获取当前提供商
     */
    fun getCurrentProvider() = getCurrentProviderType()?.let { 
        AIProviderFactory.getProvider(it) 
    }

    /**
     * 获取当前提供商的配置
     */
    fun getProviderConfig(): AIProviderConfig {
        return when (getCurrentProviderType()) {
            AIProviderFactory.ProviderType.DASHSCOPE -> AIProviderConfig(
                apiKey = dashScopeApiKey,
                model = dashScopeModel,
                temperature = temperature,
                maxTokens = maxTokens,
                timeout = timeout,
                baseUrl = dashScopeBaseUrl.takeIf { it.isNotBlank() }
            )
            AIProviderFactory.ProviderType.DEEPSEEK -> AIProviderConfig(
                apiKey = deepSeekApiKey,
                model = deepSeekModel,
                temperature = temperature,
                maxTokens = maxTokens,
                timeout = timeout,
                baseUrl = deepSeekBaseUrl.takeIf { it.isNotBlank() }
            )
            null -> AIProviderConfig(
                apiKey = "",
                model = "",
                temperature = temperature,
                maxTokens = maxTokens,
                timeout = timeout
            )
        }
    }

    /**
     * 获取指定提供商的配置
     */
    fun getProviderConfig(providerType: AIProviderFactory.ProviderType): AIProviderConfig {
        return when (providerType) {
            AIProviderFactory.ProviderType.DASHSCOPE -> AIProviderConfig(
                apiKey = dashScopeApiKey,
                model = dashScopeModel,
                temperature = temperature,
                maxTokens = maxTokens,
                timeout = timeout,
                baseUrl = dashScopeBaseUrl.takeIf { it.isNotBlank() }
            )
            AIProviderFactory.ProviderType.DEEPSEEK -> AIProviderConfig(
                apiKey = deepSeekApiKey,
                model = deepSeekModel,
                temperature = temperature,
                maxTokens = maxTokens,
                timeout = timeout,
                baseUrl = deepSeekBaseUrl.takeIf { it.isNotBlank() }
            )
        }
    }

    /**
     * 设置指定提供商的配置
     */
    fun setProviderConfig(providerType: AIProviderFactory.ProviderType, config: AIProviderConfig) {
        when (providerType) {
            AIProviderFactory.ProviderType.DASHSCOPE -> {
                dashScopeApiKey = config.apiKey
                dashScopeModel = config.model
                dashScopeBaseUrl = config.baseUrl ?: ""
            }
            AIProviderFactory.ProviderType.DEEPSEEK -> {
                deepSeekApiKey = config.apiKey
                deepSeekModel = config.model
                deepSeekBaseUrl = config.baseUrl ?: ""
            }
        }
    }

    /**
     * 获取当前提供商的API密钥
     */
    fun getCurrentApiKey(): String {
        return when (getCurrentProviderType()) {
            AIProviderFactory.ProviderType.DASHSCOPE -> dashScopeApiKey
            AIProviderFactory.ProviderType.DEEPSEEK -> deepSeekApiKey
            null -> ""
        }
    }

    /**
     * 获取当前提供商的模型
     */
    fun getCurrentModel(): String {
        return when (getCurrentProviderType()) {
            AIProviderFactory.ProviderType.DASHSCOPE -> dashScopeModel
            AIProviderFactory.ProviderType.DEEPSEEK -> deepSeekModel
            null -> ""
        }
    }

    /**
     * 获取当前提供商的Base URL
     */
    fun getCurrentBaseUrl(): String {
        return when (getCurrentProviderType()) {
            AIProviderFactory.ProviderType.DASHSCOPE -> dashScopeBaseUrl
            AIProviderFactory.ProviderType.DEEPSEEK -> deepSeekBaseUrl
            null -> ""
        }
    }

    /**
     * 设置当前提供商的API密钥
     */
    fun setCurrentApiKey(apiKey: String) {
        when (getCurrentProviderType()) {
            AIProviderFactory.ProviderType.DASHSCOPE -> dashScopeApiKey = apiKey
            AIProviderFactory.ProviderType.DEEPSEEK -> deepSeekApiKey = apiKey
            null -> {}
        }
    }

    /**
     * 设置当前提供商的模型
     */
    fun setCurrentModel(model: String) {
        when (getCurrentProviderType()) {
            AIProviderFactory.ProviderType.DASHSCOPE -> dashScopeModel = model
            AIProviderFactory.ProviderType.DEEPSEEK -> deepSeekModel = model
            null -> {}
        }
    }

    /**
     * 设置当前提供商的Base URL
     */
    fun setCurrentBaseUrl(baseUrl: String) {
        when (getCurrentProviderType()) {
            AIProviderFactory.ProviderType.DASHSCOPE -> dashScopeBaseUrl = baseUrl
            AIProviderFactory.ProviderType.DEEPSEEK -> deepSeekBaseUrl = baseUrl
            null -> {}
        }
    }

    /**
     * 获取可用的模型列表
     */
    fun getAvailableModels(): List<String> {
        return getCurrentProvider()?.getSupportedModels()?.map { it.id } ?: emptyList()
    }

    /**
     * 获取指定提供商的可用模型列表
     */
    fun getAvailableModels(providerType: AIProviderFactory.ProviderType): List<String> {
        return AIProviderFactory.getProvider(providerType)?.getSupportedModels()?.map { it.id } ?: emptyList()
    }

    /**
     * 获取模型显示名称
     */
    fun getModelDisplayName(modelId: String): String {
        return getCurrentProvider()?.getSupportedModels()
            ?.find { it.id == modelId }?.displayName ?: modelId
    }

    /**
     * 验证配置是否有效
     */
    fun isConfigValid(): Boolean {
        val provider = getCurrentProvider() ?: return false
        return provider.isConfigValid(getProviderConfig())
    }

    /**
     * 验证指定提供商的配置是否有效
     */
    fun isProviderConfigValid(providerType: AIProviderFactory.ProviderType): Boolean {
        val provider = AIProviderFactory.getProvider(providerType) ?: return false
        return provider.isConfigValid(getProviderConfig(providerType))
    }

    /**
     * 初始化默认模型
     */
    fun initializeDefaultModel() {
        // 初始化DashScope默认模型
        if (dashScopeModel.isBlank()) {
            val dashScopeProvider = AIProviderFactory.getProvider(AIProviderFactory.ProviderType.DASHSCOPE)
            dashScopeProvider?.getSupportedModels()?.firstOrNull()?.let {
                dashScopeModel = it.id
            }
        }
        
        // 初始化DeepSeek默认模型
        if (deepSeekModel.isBlank()) {
            val deepSeekProvider = AIProviderFactory.getProvider(AIProviderFactory.ProviderType.DEEPSEEK)
            deepSeekProvider?.getSupportedModels()?.firstOrNull()?.let {
                deepSeekModel = it.id
            }
        }
    }

    /**
     * 获取所有提供商的配置状态
     */
    fun getAllProviderStatus(): Map<AIProviderFactory.ProviderType, String> {
        return mapOf(
            AIProviderFactory.ProviderType.DASHSCOPE to when {
                dashScopeApiKey.isBlank() -> "未配置API密钥"
                isProviderConfigValid(AIProviderFactory.ProviderType.DASHSCOPE) -> "配置正常"
                else -> "配置无效"
            },
            AIProviderFactory.ProviderType.DEEPSEEK to when {
                deepSeekApiKey.isBlank() -> "未配置API密钥"
                isProviderConfigValid(AIProviderFactory.ProviderType.DEEPSEEK) -> "配置正常"
                else -> "配置无效"
            }
        )
    }

    companion object {
        fun getInstance(project: Project): AISettingsState {
            return project.service<AISettingsState>()
        }
    }
}